<template>
<view class="news">
  <none-data v-if="userMsgData.list.length === 0" />
  <news-item
      v-for="news in userMsgData.list"
      :key="news.id"
      :news-data="news"
      @news-options-btn-click-emit="handleNewsItemOptBtnClick"
  />
</view>
</template>

<script setup>
import newsItem from './components/news-item.vue'
import {reactive, nextTick, getCurrentInstance} from "vue";
import {getUserMsgListApi, makeUserMsgReadApi,} from "@/api/user/news.js"
import {onShow} from "@dcloudio/uni-app";
const {proxy} = getCurrentInstance();

const userMsgData = reactive({
  queryParams: {
    page: 1,
    size: 10
  },
  list: []
})

/**
 * 获取消息列表
 * @returns {Promise<void>}
 */
const getUserMsgList = async () => {
  const res = await getUserMsgListApi(userMsgData.queryParams)
  const {code, data} = res
  if (code === 200) {
    const {records} = data || {}
    records.forEach(record => {
      record.isRead = record.isRead === '1'
    })
    Array.isArray(records) && (userMsgData.list = records)
  }
}

/**
 * 消息项操作按钮点击监听
 * @param btnParams
 */
const handleNewsItemOptBtnClick = btnParams => {
  switch (btnParams.name) {
    case 'isRead':
      makeNewsRead(btnParams.newsId)
  }
}

const makeNewsRead = async (newsId) => {
  const res = await makeUserMsgReadApi(newsId)
  const {code} = res
  if (code === 200) {
    await getUserMsgList()
    await nextTick(() => {
      proxy.$forceUpdate()
    })
  }
}

onShow(() => {
  getUserMsgList()
});
</script>

<style lang="less" scoped>
</style>
